package com.huxiu.yd;

import com.android.volley.Request.Method;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.huxiu.yd.net.GsonRequest;
import com.huxiu.yd.net.NetworkConstants;
import com.huxiu.yd.net.model.Category;
import com.huxiu.yd.net.responses.CategoriesResponse;
import com.huxiu.yd.utils.ErrorResponseException;
import com.huxiu.yd.utils.LogUtils;
import com.huxiu.yd.utils.Utils;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import butterknife.ButterKnife;
import butterknife.InjectView;

/**
 * Created by yao on 15/8/20:上午12:00.
 */
public class CategoryPickerActivity extends BaseActivity
        implements OnItemClickListener {

    @InjectView(R.id.back)
    ImageView back;

    @InjectView(R.id.left_text)
    TextView leftText;

    @InjectView(R.id.title)
    TextView title;

    @InjectView(R.id.right_image)
    ImageView rightImage;

    @InjectView(R.id.right_text)
    TextView rightText;

    @InjectView(R.id.list)
    ListView list;

    private int launchType;

    public static final int LAUNCH_TYPE_CATEGORIES = 0;

    public static final int LAUNCH_TYPE_COMPANIES = 1;

    public static final int LAUNCH_TYPE_PRODUCTS = 2;

    private Category category;

    private Category company;

    private Category product;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.picker_activity);
        ButterKnife.inject(this);
        launchType = getIntent().getIntExtra("launch_type", LAUNCH_TYPE_CATEGORIES);
        back.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        adapter = new CategoryAdapter();
        list.setAdapter(adapter);
        list.setOnItemClickListener(this);
        bindTitle();
        getServerData();
    }

    private void bindTitle() {
        switch (launchType) {
            case LAUNCH_TYPE_CATEGORIES:
                title.setText(R.string.select_category);
                break;
            case LAUNCH_TYPE_COMPANIES:
                title.setText(R.string.select_company);
                break;
            case LAUNCH_TYPE_PRODUCTS:
                title.setText(R.string.select_product);
                break;
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        LogUtils.d("onItemClick, launchType is " + launchType);
        switch (launchType) {
            case LAUNCH_TYPE_CATEGORIES:
                category = dataItems.get(position);
                launchType++;
                getServerData();
                break;
            case LAUNCH_TYPE_COMPANIES:
                company = dataItems.get(position);
                launchType++;
                getServerData();
                break;
            case LAUNCH_TYPE_PRODUCTS:
                product = dataItems.get(position);
                setResult(RESULT_OK);
                finish();
                break;
        }
    }

    private List<Category> dataItems = new ArrayList<>();

    private CategoryAdapter adapter;

    private class CategoryAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return dataItems.size();
        }

        @Override
        public Category getItem(int position) {
            return dataItems.get(position);
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = convertView;
            if (view == null) {
                view = getLayoutInflater().inflate(R.layout.picker_list_item, parent, false);
            }
            TextView textView = (TextView) view.findViewById(R.id.text);
            LogUtils.d("getView, item is " + getItem(position));
            if (launchType == LAUNCH_TYPE_CATEGORIES || launchType == LAUNCH_TYPE_PRODUCTS) {
                textView.setText(getItem(position).name);
            } else if (launchType == LAUNCH_TYPE_COMPANIES) {
                textView.setText(getItem(position).title);
            }
            View rightArrow = view.findViewById(R.id.right_arrow);
            rightArrow.setVisibility(launchType == LAUNCH_TYPE_PRODUCTS ? View.GONE : View.VISIBLE);
            return view;
        }
    }

    private void getServerData() {
        String url = NetworkConstants.GOODS_URL;
        Map<String, String> params = new LinkedHashMap<>();
        String act = "category";
        if (launchType == LAUNCH_TYPE_COMPANIES) {
            act = "company";
        }
        if (launchType == LAUNCH_TYPE_PRODUCTS) {
            act = "product";
        }
        params.put("act", act);
        if (category != null) {
            params.put("category_id", category.id);
        }
        if (company != null) {
            params.put("company_id", company.id);
        }
        for (String key : params.keySet()) {
            LogUtils.d(key + " : " + params.get(key));
        }
        GsonRequest<CategoriesResponse> request = new GsonRequest<>(url, Method.POST,
                CategoriesResponse.class, true, params, new Listener<CategoriesResponse>() {
            @Override
            public void onResponse(CategoriesResponse response) {
                dismissProgress();
                if (response.isSuccess()) {
                    List<Category> data = Arrays.asList(response.data);
                    dataItems.clear();
                    dataItems.addAll(data);
                } else {
                    Utils.showToast(response.msg);
                    launchType--;
                }
                adapter.notifyDataSetChanged();
                bindTitle();
            }
        }, mErrorListener);
        showProgress();
        mQueue.add(request);
//        mQueue.start();
    }

    protected ErrorListener mErrorListener = new ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            dismissProgress();
            launchType--;
            Throwable t = error.getCause();
            if (t instanceof ErrorResponseException) {
                Utils.showToast(error.getMessage());
            } else {
                Utils.showToast(R.string.generic_failure);
            }
        }
    };

    @Override
    public void finish() {
        Intent intent = new Intent();
        if (category != null) {
            intent.putExtra("category", category);
        }
        if (company != null) {
            intent.putExtra("company", company);
        }
        if (product != null) {
            intent.putExtra("product", product);
        }
        setResult(RESULT_OK, intent);
        super.finish();
    }
}
